<template>
  <Dialog v-model="dialogVisible" title="材料管理" width="1200px">
    <!-- 考生信息 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <span>考生信息</span>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="姓名">
          {{ candidateInfo.candidateName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="身份证号">
          {{ candidateInfo.idCard || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ candidateInfo.phone || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="申报职业">
          {{ candidateInfo.professionName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="申报等级">
          {{ candidateInfo.skillLevel || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="报名状态">
          <el-tag :type="getStatusColor(candidateInfo.auditStatus)">
            {{ getStatusName(candidateInfo.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    
    <!-- 材料管理 -->
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 材料列表 -->
      <el-tab-pane label="材料列表" name="list">
        <div style="margin-bottom: 15px;">
          <el-space>
            <el-button type="primary" @click="showUploadDialog">
              上传材料
            </el-button>
            <el-button type="success" @click="batchDownload" :disabled="selectedMaterials.length === 0">
              批量下载 ({{ selectedMaterials.length }})
            </el-button>
            <el-button type="danger" @click="batchDelete" :disabled="selectedMaterials.length === 0">
              批量删除
            </el-button>
            <el-button @click="refreshMaterials">
              刷新
            </el-button>
          </el-space>
        </div>
        
        <el-table 
          :data="materialList" 
          border 
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="materialName" label="材料名称" width="200" />
          <el-table-column prop="materialType" label="材料类型" width="120">
            <template #default="{ row }">
              <el-tag>{{ getMaterialTypeName(row.materialType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fileName" label="文件名" width="200" />
          <el-table-column prop="fileSize" label="文件大小" width="100">
            <template #default="{ row }">
              {{ formatFileSize(row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" width="150" />
          <el-table-column prop="auditStatus" label="审核状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getAuditStatusColor(row.auditStatus)">
                {{ getAuditStatusName(row.auditStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="auditComments" label="审核意见" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="previewMaterial(row)">
                预览
              </el-button>
              <el-button link type="success" size="small" @click="downloadMaterial(row)">
                下载
              </el-button>
              <el-button link type="warning" size="small" @click="auditMaterial(row)">
                审核
              </el-button>
              <el-button link type="danger" size="small" @click="deleteMaterial(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <!-- 材料要求 -->
      <el-tab-pane label="材料要求" name="requirements">
        <el-alert
          title="根据申报职业和等级，需要提供以下材料："
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <el-table :data="materialRequirements" border style="width: 100%">
          <el-table-column prop="materialName" label="材料名称" width="200" />
          <el-table-column prop="materialType" label="材料类型" width="120">
            <template #default="{ row }">
              <el-tag>{{ getMaterialTypeName(row.materialType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isRequired" label="是否必需" width="100">
            <template #default="{ row }">
              <el-tag :type="row.isRequired ? 'danger' : 'info'">
                {{ row.isRequired ? '必需' : '可选' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="材料说明" />
          <el-table-column prop="submitStatus" label="提交状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getSubmitStatusColor(row.submitStatus)">
                {{ getSubmitStatusName(row.submitStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button 
                link 
                type="primary" 
                size="small" 
                @click="uploadSpecificMaterial(row)"
                v-if="row.submitStatus !== 'submitted'"
              >
                上传
              </el-button>
              <el-button 
                link 
                type="success" 
                size="small" 
                @click="viewSubmittedMaterial(row)"
                v-else
              >
                查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      
      <!-- 审核记录 -->
      <el-tab-pane label="审核记录" name="audit">
        <el-timeline>
          <el-timeline-item
            v-for="(record, index) in auditHistory"
            :key="index"
            :timestamp="record.auditTime"
            :type="getAuditTimelineType(record.auditResult)"
          >
            <el-card>
              <h4>{{ record.materialName }}</h4>
              <p><strong>审核人：</strong>{{ record.auditor }}</p>
              <p><strong>审核结果：</strong>
                <el-tag :type="getAuditResultColor(record.auditResult)">
                  {{ getAuditResultName(record.auditResult) }}
                </el-tag>
              </p>
              <p v-if="record.auditComments"><strong>审核意见：</strong>{{ record.auditComments }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传材料" width="600px">
      <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="120px">
        <el-form-item label="材料类型" prop="materialType">
          <el-select v-model="uploadForm.materialType" placeholder="请选择材料类型">
            <el-option label="身份证" value="id_card" />
            <el-option label="学历证书" value="diploma" />
            <el-option label="工作证明" value="work_proof" />
            <el-option label="技能证书" value="skill_cert" />
            <el-option label="照片" value="photo" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="材料名称" prop="materialName">
          <el-input v-model="uploadForm.materialName" placeholder="请输入材料名称" />
        </el-form-item>
        
        <el-form-item label="材料说明" prop="description">
          <el-input
            v-model="uploadForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入材料说明"
          />
        </el-form-item>
        
        <el-form-item label="选择文件" prop="files">
          <el-upload
            ref="uploadRef"
            :limit="5"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-remove="beforeFileRemove"
            accept=".jpg,.jpeg,.png,.pdf,.doc,.docx"
            multiple
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持jpg/png/pdf/doc/docx格式，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload" :loading="uploadLoading">确定上传</el-button>
      </template>
    </el-dialog>
    
    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="材料审核" width="500px">
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.auditResult">
            <el-radio value="pass">通过</el-radio>
            <el-radio value="reject">不通过</el-radio>
            <el-radio value="resubmit">需重新提交</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核意见" prop="auditComments">
          <el-input
            v-model="auditForm.auditComments"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit" :loading="auditLoading">确定</el-button>
      </template>
    </el-dialog>
    
    <template #footer>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const dialogVisible = ref(false)
const activeTab = ref('list')
const uploadDialogVisible = ref(false)
const auditDialogVisible = ref(false)
const uploadLoading = ref(false)
const auditLoading = ref(false)
const uploadFormRef = ref()
const auditFormRef = ref()
const uploadRef = ref()

const candidateInfo = ref({
  candidateName: '',
  idCard: '',
  phone: '',
  professionName: '',
  skillLevel: null,
  auditStatus: null
})

const selectedMaterials = ref([])
const currentAuditMaterial = ref(null)

const materialList = ref([
  {
    id: 1,
    materialName: '身份证',
    materialType: 'id_card',
    fileName: '身份证.jpg',
    fileSize: 2048576,
    uploadTime: '2023-12-01 10:00:00',
    auditStatus: 'pass',
    auditComments: '身份证清晰，信息完整'
  },
  {
    id: 2,
    materialName: '学历证书',
    materialType: 'diploma',
    fileName: '学历证书.pdf',
    fileSize: 1536000,
    uploadTime: '2023-12-01 10:30:00',
    auditStatus: 'pending',
    auditComments: ''
  },
  {
    id: 3,
    materialName: '工作证明',
    materialType: 'work_proof',
    fileName: '工作证明.pdf',
    fileSize: 512000,
    uploadTime: '2023-12-01 11:00:00',
    auditStatus: 'reject',
    auditComments: '工作年限不符合要求'
  }
])

const materialRequirements = ref([
  {
    materialName: '身份证',
    materialType: 'id_card',
    isRequired: true,
    description: '身份证正反面清晰照片',
    submitStatus: 'submitted'
  },
  {
    materialName: '学历证书',
    materialType: 'diploma',
    isRequired: true,
    description: '最高学历证书扫描件',
    submitStatus: 'submitted'
  },
  {
    materialName: '工作证明',
    materialType: 'work_proof',
    isRequired: true,
    description: '相关工作经验证明',
    submitStatus: 'submitted'
  },
  {
    materialName: '技能证书',
    materialType: 'skill_cert',
    isRequired: false,
    description: '相关技能等级证书',
    submitStatus: 'not_submitted'
  }
])

const auditHistory = ref([
  {
    materialName: '工作证明',
    auditor: '审核员A',
    auditTime: '2023-12-01 14:00:00',
    auditResult: 'reject',
    auditComments: '工作年限不符合要求，需提供更详细的工作证明'
  },
  {
    materialName: '身份证',
    auditor: '审核员B',
    auditTime: '2023-12-01 11:00:00',
    auditResult: 'pass',
    auditComments: '身份证清晰，信息完整'
  }
])

const uploadForm = ref({
  materialType: '',
  materialName: '',
  description: '',
  files: []
})

const uploadRules = ref({
  materialType: [{ required: true, message: '请选择材料类型', trigger: 'change' }],
  materialName: [{ required: true, message: '请输入材料名称', trigger: 'blur' }],
  files: [{ required: true, message: '请选择要上传的文件', trigger: 'change' }]
})

const auditForm = ref({
  auditResult: '',
  auditComments: ''
})

const auditRules = ref({
  auditResult: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  auditComments: [{ required: true, message: '请输入审核意见', trigger: 'blur' }]
})

const getLevelName = (level: number) => {
  const levelMap = { 1: '初级', 2: '中级', 3: '高级', 4: '技师', 5: '高级技师' }
  return levelMap[level] || '-'
}

const getStatusName = (status: number) => {
  const statusMap = { 1: '已报名', 2: '已确认', 3: '已取消' }
  return statusMap[status] || '-'
}

const getStatusColor = (status: number) => {
  const colorMap = { 1: 'warning', 2: 'success', 3: 'danger' }
  return colorMap[status] || 'info'
}

const getMaterialTypeName = (type: string) => {
  const typeMap = {
    'id_card': '身份证',
    'diploma': '学历证书',
    'work_proof': '工作证明',
    'skill_cert': '技能证书',
    'photo': '照片',
    'other': '其他'
  }
  return typeMap[type] || type
}

const getAuditStatusName = (status: string) => {
  const statusMap = {
    'pending': '待审核',
    'pass': '审核通过',
    'reject': '审核不通过',
    'resubmit': '需重新提交'
  }
  return statusMap[status] || status
}

const getAuditStatusColor = (status: string) => {
  const colorMap = {
    'pending': 'warning',
    'pass': 'success',
    'reject': 'danger',
    'resubmit': 'warning'
  }
  return colorMap[status] || 'info'
}

const getSubmitStatusName = (status: string) => {
  const statusMap = {
    'not_submitted': '未提交',
    'submitted': '已提交',
    'approved': '已审核'
  }
  return statusMap[status] || status
}

const getSubmitStatusColor = (status: string) => {
  const colorMap = {
    'not_submitted': 'danger',
    'submitted': 'warning',
    'approved': 'success'
  }
  return colorMap[status] || 'info'
}

const getAuditResultName = (result: string) => {
  return getAuditStatusName(result)
}

const getAuditResultColor = (result: string) => {
  return getAuditStatusColor(result)
}

const getAuditTimelineType = (result: string) => {
  const typeMap = {
    'pass': 'success',
    'reject': 'danger',
    'resubmit': 'warning'
  }
  return typeMap[result] || 'primary'
}

const formatFileSize = (size: number) => {
  if (size < 1024) return size + 'B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(1) + 'KB'
  return (size / (1024 * 1024)).toFixed(1) + 'MB'
}

const handleSelectionChange = (selection: any[]) => {
  selectedMaterials.value = selection
}

const showUploadDialog = () => {
  uploadDialogVisible.value = true
  uploadForm.value = {
    materialType: '',
    materialName: '',
    description: '',
    files: []
  }
}

const handleFileChange = (file: any, fileList: any[]) => {
  uploadForm.value.files = fileList
}

const beforeFileRemove = () => {
  return true
}

const submitUpload = async () => {
  const elForm = uploadFormRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  if (uploadForm.value.files.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  uploadLoading.value = true
  try {
    // TODO: 上传文件
    console.log('上传材料:', uploadForm.value)
    
    uploadDialogVisible.value = false
    refreshMaterials()
    ElMessage.success('材料上传成功')
  } finally {
    uploadLoading.value = false
  }
}

const previewMaterial = (material: any) => {
  // TODO: 预览文件
  ElMessage.info(`预览文件: ${material.fileName}`)
}

const downloadMaterial = (material: any) => {
  // TODO: 下载文件
  ElMessage.success(`下载文件: ${material.fileName}`)
}

const auditMaterial = (material: any) => {
  currentAuditMaterial.value = material
  auditForm.value = {
    auditResult: material.auditStatus === 'pending' ? '' : material.auditStatus,
    auditComments: material.auditComments
  }
  auditDialogVisible.value = true
}

const submitAudit = async () => {
  const elForm = auditFormRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  auditLoading.value = true
  try {
    // TODO: 提交审核结果
    console.log('审核材料:', {
      materialId: currentAuditMaterial.value.id,
      ...auditForm.value
    })
    
    // 更新本地数据
    currentAuditMaterial.value.auditStatus = auditForm.value.auditResult
    currentAuditMaterial.value.auditComments = auditForm.value.auditComments
    
    auditDialogVisible.value = false
    ElMessage.success('审核完成')
  } finally {
    auditLoading.value = false
  }
}

const deleteMaterial = (material: any) => {
  ElMessageBox.confirm(`确定要删除材料"${material.materialName}"吗？`, '确认删除', {
    type: 'warning'
  }).then(() => {
    // TODO: 删除材料
    const index = materialList.value.findIndex(item => item.id === material.id)
    if (index > -1) {
      materialList.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const batchDownload = () => {
  // TODO: 批量下载
  ElMessage.success(`开始下载 ${selectedMaterials.value.length} 个文件`)
}

const batchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedMaterials.value.length} 个材料吗？`, '确认删除', {
    type: 'warning'
  }).then(() => {
    // TODO: 批量删除
    selectedMaterials.value.forEach(material => {
      const index = materialList.value.findIndex(item => item.id === material.id)
      if (index > -1) {
        materialList.value.splice(index, 1)
      }
    })
    selectedMaterials.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const refreshMaterials = () => {
  // TODO: 刷新材料列表
  ElMessage.success('材料列表已刷新')
}

const uploadSpecificMaterial = (requirement: any) => {
  uploadForm.value.materialType = requirement.materialType
  uploadForm.value.materialName = requirement.materialName
  uploadDialogVisible.value = true
}

const viewSubmittedMaterial = (requirement: any) => {
  const material = materialList.value.find(item => item.materialType === requirement.materialType)
  if (material) {
    previewMaterial(material)
  }
}

const open = (data?: any) => {
  dialogVisible.value = true
  if (data) {
    // 映射考生数据字段
    candidateInfo.value = {
      candidateName: data.name || '',
      idCard: data.idNumber || '',
      phone: data.mobile || '',
      professionName: data.appliedProfession || '',
      skillLevel: data.appliedLevel || '',
      auditStatus: data.registrationStatus || null
    }
  }
  activeTab.value = 'list'
}

defineExpose({ open })
</script> 